/**
 * @author: gao
 * @create-date: 2025/3/4 15:17
 */

public class Heap {
    //储存数据
    public int[] elem;
    //存放有效数据的个数
    public int usedSize;

    public Heap() {
        elem = new int[10];
    }

    //数组初始化
    public void Initial(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    //堆的创建
    public void CreateHeap() {
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            //shiftdown(parent, usedSize);
            shiftup(parent,usedSize);
        }
    }

    //向下调整
    private void shiftdown(int parent, int usedSize) {
        int child = 2 * parent + 1;
        while (child < usedSize) {
            if (child + 1 < usedSize && elem[child] < elem[child + 1]) {
                child++;
            }
            //走到这里，child下标一定是左右孩子最大值的下标
            if (elem[child] > elem[parent]) {
                //交换
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }

    //向下调整
    private void shiftup(int parent, int usedSize) {
        int child = 2 * parent + 1;
        while (child < usedSize) {
            if (child + 1 < usedSize && elem[child] > elem[child + 1]) {
                child++;
            }
            //走到这里，child下标一定是左右孩子最大值的下标
            if (elem[child] < elem[parent]) {
                //交换
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }
}